from Products.Five import BrowserView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
import json
from Products.CMFPlone.utils import base_hasattr
from Products.ePubBook.interfaces import IBook
from Products.ePubBook import ePubBookMessageFactory as _
from Products.CMFCore.WorkflowCore import WorkflowException
from Products.CMFPlone.utils import log
from DateTime.DateTime import DateTime
#For upload files
from Acquisition import aq_inner, aq_base, aq_parent
from Products.CMFPlone.FactoryTool import TempFolder
from Products.CMFCore.utils import getToolByName


class InfoView(BrowserView):
    """ book information page
    """
    template = ViewPageTemplateFile('infoview.pt')
    
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)        
    def directory(self):
        return ('1.Jamie Zawinski 1','2.Brad Fitzpatrick 37','3.Douglas Crockford 69')

    
class PagesView(BrowserView):
    """ book information page
    """
    template = ViewPageTemplateFile('pagesview.pt')
    
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        
        
class AppView(BrowserView):
    """ App Information view
    """
    template = ViewPageTemplateFile('appview.pt')
    
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
class FullView(BrowserView):
    """shelf book full view
    """
    template = ViewPageTemplateFile('fullview.pt')
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        
class PreView(BrowserView):
    """Book Preview
    """
    template = ViewPageTemplateFile('preview.pt')
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        self.context =context
    def reviewState(self):
        return bookReviewState(aq_inner(self.context))  
    
class PayView(BrowserView):
    """Book PayView
    """
    template = ViewPageTemplateFile('payview.pt')
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
class AppPreview(BrowserView):
    """Book AppPreview
    """
    template = ViewPageTemplateFile('apppreview.pt')
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        self.context = context
    def bookReviewState(self):
        parent = aq_parent(aq_inner(self.context))
        return bookReviewState(parent)    
    
class HistoryView(BrowserView):
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        self.context = context
    def workflowHistory(self, complete=True):
        """Return workflow history of this context.

        """
        context = aq_inner(self.context)
        # check if the current user has the proper permissions
        mt = getToolByName(self, 'portal_membership')
        if not (mt.checkPermission('Request review', context) or
            mt.checkPermission('Review portal content', context)):
            return []

        workflow = getToolByName(context, 'portal_workflow')
        membership = getToolByName(context, 'portal_membership')

        review_history = []

        try:
            # get total history
            review_history = workflow.getInfoFor(context, 'review_history')
            action = workflow.getInfoFor(context, 'action')
#            actor = workflow.getInfoFor(context, 'actor')
#            comments  = workflow.getInfoFor(context, 'comments')
#            time   = workflow.getInfoFor(context, 'time')
#            print action
#            print actor
#            print comments
#            print time
            if not complete:
                # filter out automatic transitions.
                review_history = [r for r in review_history if r['action']]
            else:
                review_history = list(review_history)

            portal_type = context.portal_type
            anon = _(u'label_anonymous_user', default=u'Anonymous User')

            for r in review_history:
                r['type'] = 'workflow'
                r['transition_title'] = workflow.getTitleForTransitionOnType(r['action'],
                                                                             portal_type)
                actorid = r['actor']
                r['actorid'] = actorid
                if actorid is None:
                    # action performed by an anonymous user
                    r['actor'] = {'username': anon, 'fullname': anon}
                    r['actor_home'] = ''
                else:
                    r['actor'] = membership.getMemberInfo(actorid)
                    if r['actor'] is not None:
                        r['actor_home'] = self.navigation_root_url + '/author/' + actorid
                    else:
                        # member info is not available
                        # the user was probably deleted
                        r['actor_home'] = ''
            review_history.reverse()

        except WorkflowException:
            log('plone.app.layout.viewlets.content: '
                '%s has no associated workflow' % context.absolute_url(),
                severity=logging.DEBUG)

        return review_history
        
#Review
class InfoReview(BrowserView):
    template = ViewPageTemplateFile('inforeview.pt')    
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
class PagesReview(BrowserView):
    template = ViewPageTemplateFile('pagesreview.pt')    
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
class AppReview(BrowserView):
    template = ViewPageTemplateFile('appreview.pt')
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)    
    
class BookDetailJson:
    def __init__(self,context,request):
        self.context = context
        self.request = request
    def __call__(self):
        uid = self.request.id
        if uid == '':
            return '{"Status":"Error","Message":"Book id Null"}' 
        book = self.context.reference_catalog.lookupObject(uid)
        
        if book==None or not IBook.providedBy(book):
            return '{"Status":"Error","Message":"Book id  error"}'
        if base_hasattr(self.request,'pages'):
            date = None
            if base_hasattr(self.request, 'updated'):
                try:
                    updated = self.request.updated
                    date = DateTime(updated)
                except:
                    return '{"Status":"Error","Message":"updated format error"}'
            return json.dumps(self.formatPages(book,date))
        elif base_hasattr(self.request,'preview'):
            return json.dumps(self.formatPreview(book))
        else:
            return json.dumps(self.formatDetail(book,base_hasattr(self.request,'full')))
    def formatPreview(self,book):
        path ='/'.join(book.getPhysicalPath())
        results = self.context.portal_catalog.searchResults(path=path,Type="EpubPage",review_state='published')
        pages=[]
        i = 0 
        for page in results:
            pages.append('%s/preview.%s' % (page.id,page.id))
            if i==4:
                break
            else:
                i=i+1
        descDict={}
        descDict['root'] = '%s' % book.absolute_url()
        descDict['pages'] = pages
        return descDict
        
    def formatDetail(self, book,isFull):
        bookurl = book.absolute_url()
        descDict = {}
        descDict['id'] = book.UID()
        if bookurl.find('/bookshelf') == -1:
            descDict['title'] = book.title
        else:
            descDict['title'] = '[%s]' % book.title
        descDict['minicover'] = '%s/cover_mini' % bookurl
        if isFull:
            descDict['cover'] = '%s/cover_large' % bookurl
            descDict['description'] =  book.Description()
            descDict['pages'] = len(book.objectIds())-1 # except app
            descDict['author']= book.Creator()
            #TODO 
            descDict['price'] = '0.00'
            descDict['status'] = 3
            descDict['level'] = 4
            descDict['rating'] = '12+'
            descDict['buy_status'] = 1
        return descDict
    
    def __getPages(self,book):
        return book.listFolderContents(contentFilter={"portal_type" : "EpubPage"})
    
    def formatPages(self,book,date):
        pages=[]
        minipages=[]
        for page in self.__getPages(book):
            # has updated para and this page is old
            #print page.modified()
            #print date
            #print page.modified() - date
            if date!= None and (page.modified()- date) < -0.333333333:
                continue
            pages.append(page.id)
            minipages.append('%s/mini.%s' % (page.id,page.id))
        descDict={}
        descDict['root'] = '%s' % book.absolute_url()
        descDict['pages'] = pages
        descDict['minipages'] = minipages
        descDict['xml'] = 'pages.plist'
        return descDict

def isTemporary(obj):
    """Check to see if an object is temporary"""
    parent = aq_base(aq_parent(aq_inner(obj)))
    return hasattr(parent, 'meta_type') and parent.meta_type == TempFolder.meta_type

def bookReviewState(obj):
    wflow = getToolByName(obj, "portal_workflow")
    if wflow is not None:
        review_state = wflow.getInfoFor(obj, "review_state")
    else:
        review_state = None
    return review_state

class PagesEdit(BrowserView):
    template = ViewPageTemplateFile('pagesedit.pt')
    
    def __init__(self, context, request):
        BrowserView.__init__(self, context, request)
        self.context = context
        session = request.get('SESSION', None)
        # empty typeupload and mediaupload session 
        # since the portlet don't use it, but another app could
        if session :
            if session.has_key('typeupload') :
                session.delete('typeupload')
            if session.has_key('mediaupload') :
                session.delete('mediaupload')
        self.ploneview = context.restrictedTraverse('@@plone')
        self.pm = getToolByName(context, 'portal_membership')
    
    @property
    def available(self):
        context = aq_inner(self.context)
        if self.ploneview.isStructuralFolder() and \
           self.pm.checkPermission('Add portal content', context) and \
           not isTemporary(context) :
            return True
        return False
    
    def getUploadUrl(self):
        """
        return upload url
        in current folder
        """
        context = aq_inner(self.context)
        folder_url = self.ploneview.getCurrentFolderUrl()                      
        return '%s/@@quick_upload' %folder_url
    
    def getDataForUploadUrl(self):
        data_url = ''
        data_url+= 'typeupload=EpubPage&'      
        data_url+= 'mediaupload=image'  
        return data_url  
    
        